#!/usr/bin/env python
import sys, os
from liwe.module import LiweModule

from liwe.tree import Tree
from liwe.utils import UpdatePos

class AddressBook ( LiweModule ):
	def __init__ ( self, liwe ):
		super ( AddressBook, self ).__init__ ( liwe, "address_book" )
		self.dbm = self.liwe.dbm
		self.tree = Tree ( liwe )

	# ADMIN METHODS  -------------------------------------------------------------------



	def list_importable ( self ):
		resp = self.dbm.all_rows ( 'address_book_import_user' , '*' )
		if not resp :
			resp = []
		return resp
	#{{{ PROFILE
	#{{{def set_profile ( self, uid = 0, name = "", lastname = "",  email = "", phone = "",fax ="", level = 0, discount = "", tax_code ="" , vat_code = "", logo = "", note = "", owner = 0 ):
	def set_profile ( self, id_profile = 0, uid = 0, name = "", lastname = "",  email = None, phone = None, cell =  None, fax= None, level = None, 
			  discount = None, tax_code = None , vat_code = None, addr1 = None, zip_code = None, city  = None, prov = None,
			  country = None, logo = None, note = None, owner = 0, id_categ = None, company = None, individual = None ):

		values = {
					"uid"  : uid,
					"name" : name,
					"lastname" : lastname,
					"owner" : owner 
				}
		if not ( email is  None ): values [ 'email' ] = email
		if not ( phone is  None ): values [ 'phone' ] = phone
		if not ( cell is  None ): values [ 'cell' ] = cell
		if not ( fax is  None ): values [ 'fax' ] = fax
		if not ( level is  None ): values [ 'level' ] = level
		if not ( discount is  None ): values [ 'discount' ] = discount
		if not ( tax_code is  None ): values [ 'tax_code' ] = tax_code
		if not ( vat_code is  None ): values [ 'vat_code' ] = vat_code
		if not ( addr1 is  None ): values [ 'addr1' ] = addr1
		if not ( zip_code is  None ): values [ 'zip_code' ] = zip_code
		if not ( city is  None ): values [ 'city' ] = city
		if not ( prov is  None ): values [ 'prov' ] = prov
		if not ( country is  None ): values [ 'country' ] = country
		if not ( logo is  None ): values [ 'logo' ] = logo
		if not ( note is  None ): values [ 'note' ] = note
		if not ( company is  None ): values [ 'company' ] = company
		if not ( individual is  None ): values [ 'individual' ] = individual

		if not owner : 
			values [ 'owner' ] = self.liwe.pyhp.session.data.get ( "uid", 0 )

		#check exsit uid
		if not id_profile :
			#create
			values [ 'created' ] =  '*NOW()'
			self.dbm.insert ( "address_book_profile", values ) 
			values [ 'id_profile' ] = self.dbm.insert_id()
		else:
			conds = "id_profile = %s " % id_profile
			self.dbm.update ( "address_book_profile", values, conds )

		return values
	#}}}
	#{{{def get_profile ( self, id_profile = 0, uid = 0 ):
	def get_profile ( self, id_profile = 0, uid = 0 ):
		if not id_profile and not uid : return []
		conds = []
		
		if id_profile : conds.append ( 'id_profile = %s' % id_profile )
		if uid : conds.append ( 'uid = %s' % uid )
		
		profile = self.dbm.single_row ( "address_book_profile", "*", ' and '.join ( conds ) )
		"""
		profile [ 'stati' ] = self.list_stati()
		profile [ 'regioni' ] = self.list_regioni()
		profile [ 'comu_list' ] = []
		profile [ 'cap_list' ] = []
		if profile [ 'prov' ] : profile [ 'comu_list' ] = self.comune_search ( profile [ 'prov' ] )
		if profile [ 'prov' ] and profile [ 'city' ] : profile [ 'cap_list' ] = self.cap_search ( profile [ 'prov' ], profile [ 'city' ] )
		"""
		return profile


	#}}}
	#{{{def del_profile ( self, uids = "" ):
	def del_profile ( self, uids = "" ):

		ids = uids.split ( "|" )
		str_ids = " ,".join ( ids )
	
		self.dbm.delete ( "address_book_profile", "id_profile IN ( %s )" % str_ids )
	#}}}
	#{{{def list_profile ( self, name = '', lastname = '', level = 0, tax_code = '', vat_code = '',quant = 10 start_point = 0, do_count = 0 ):
	def list_profile ( self, uid = 0, name = '', lastname = '', level = 0, email = '', addr1 = '', prov = '', city = '', country = '', zip_code = '', id_categ = 0, 
						vat_code = '', tax_code = '', company = -1, individual = -1, quant = 10, start_point = 0, do_count = 0 ):
		conds = []
		if uid: conds.append ( "uid = %s" % uid )
		if name: conds.append ( "name like '%%%s%%'" % name )
		if lastname: conds.append ( "lastname like '%%%s%%'" % lastname )
		if level: conds.append ( "level = %s" % level )
		if id_categ: conds.append ( "id_categ = %s" % id_categ )
		if email: conds.append ( "email like '%%%s%%'" % email )
		if addr1: conds.append ( "addr1 like '%%%s%%'" % addr1 )
		if prov: conds.append ( "prov like '%%%s%%'" % prov )
		if city: conds.append ( "city like '%%%s%%'" % city )
		if country: conds.append ( "country like '%%%s%%'" % country )
		if zip_code: conds.append ( "zip_code like '%%%s%%'" % zip_code )
		if vat_code: conds.append ( "vat_code like '%%%s%%'" % vat_code )
		if tax_code: conds.append ( "tax_code like '%%%s%%'" % tax_code )
		if company <> -1 : conds.append ( "company = %s" % company )
		if individual <> -1 : conds.append ( "individual = %s" % individual )

		#if  self.liwe.pyhp.session.data.get ( "uid", 0 ) != 1:
			#conds.append ( 'owner = %s' %  self.liwe.pyhp.session.data.get ( "uid", 0 ) )
	
		extras = ' ORDER BY lastname, name'	
		tot_rows = self.dbm.count ( 'address_book_profile', 'id_profile', ' AND '.join ( conds ) )
		if do_count:
			extras += " LIMIT %s,%s" % ( start_point, quant )
	
			
		resp = self.dbm.all_rows ( 'address_book_profile', '*', ' AND '.join ( conds ), extras = extras, debug = self.debug() )
		if not resp:
			resp = [] 
		return { "rows" : resp, "tot_rows" : tot_rows }
	#}}}
	#}}}
	#{{{ ADDRESS
	#{{{def set_adress ( self, id_address = 0, id_profile = 0, id_addr_kind = 0, addr1 = "", 
	def set_address ( self, id_address = 0, id_profile = 0, id_addr_kind = 0, addr1 = "", addr2 = "", zip_code = "", city  = "", prov = "", country = "", phone = "", mail = "", owner = 0 ):

		if not id_profile: return

		values = { 'id_profile' : id_profile,
			   'id_addr_kind' : id_addr_kind,
			   'addr1' : addr1,
			   'addr2' : addr2,
			   'zip_code' : zip_code,
			   'city' : city,
			   'prov' : prov,
			   'country' : country,
			   'phone' : phone,
			   'mail' : mail,
			   'owner' : owner
			}

		if not owner : 
			values [ 'owner' ] = self.liwe.pyhp.session.data.get ( "id_profile", 0 )

		if not id_address:
			#create
			values [ 'created' ] =  '*NOW()'
			self.dbm.insert  ( 'address_book_address', values )
			values [ 'id' ] = self.dbm.insert_id()
			return values

		self.dbm.update ( 'address_book_address', values, 'id = %s' % id_address )
		values [ 'id' ] = id_address
		return values
	#}}}
	#{{{def get_address ( self, id_address = 0, uid = 0 ):
	def get_address ( self, id_address = 0, id_profile = 0, get_default = 0 ):
		#if not id_address and not id_profile : return []
		if not id_address and not id_profile and not get_default : return []
		
		conds = []
		conds.append ( 'id = %s' % id_address )
		
		if id_profile: conds.append ( 'id_profile =  %s' % id_profile )
		
		resp =  self.dbm.single_row ( 'address_book_address', '*', ' and '.join ( conds ), debug = self.debug() )
	
		
		if not resp and get_default:
			uid = self.liwe.pyhp.session.data.get ( "uid", 0 )
			profile = self.get_profile ( uid = uid ) 
			resp = profile 
		return resp
	#}}}		
	#{{{def del_address ( self, ids = 0 ):
	def del_address ( self, ids = 0 ):
		ids = ids.split ( "|" )
		str_ids = " ,".join ( ids )
		
		self.dbm.delete ( "address_book_address", "id IN ( %s )" % str_ids )
			
	#}}}		
	#{{{def list_address ( self, addr1 = '', addr2 = '', zip_code = '', city = '', prov = '', country = '', phone = '', quant = 10 start_point = 0, do_count = 0 ):
	def list_address ( self, id_profile = 0 , addr1 = '', addr2 = '', zip_code = '', city = '', prov = '', country = '', phone = '', quant = 10, start_point = 0, do_count = 0 ):
		conds = []
		if id_profile: conds.append ( "id_profile = %s" % id_profile )
		if addr1: conds.append ( "addr1 like '%%%s%%'" % addr1 )
		if addr2: conds.append ( "addr2 like '%%%s%%'" % addr2 )
		if zip_code: conds.append ( "zip_code like '%%%s%%'" % zip_code )
		if prov: conds.append ( "prov like '%%%s%%'" % prov )
		if country: conds.append ( "country like '%%%s%%'" % country )
		if phone: conds.append ( "phone like '%%%s%%'" % phone )

		#if  self.liwe.pyhp.session.data.get ( "uid", 0 ) != 1:
			#conds.append ( 'owner = %s' %  self.liwe.pyhp.session.data.get ( "uid", 0 ) )

		tot_rows = self.dbm.count ( 'address_book_list_address', 'id_profile', ' AND '.join ( conds ) )
		extras = ''	
		if do_count:
			extras = " LIMIT %s,%s" % ( start_point, quant )
			
		resp = self.dbm.all_rows ( 'address_book_list_address', '*', ' AND '.join ( conds ), extras = extras )
		if not resp:
			resp = [] 
		return { "rows" : resp, "tot_rows" : tot_rows }
	#}}}
	def address_select ( self ):
		uid = self.liwe.pyhp.session.data.get ( "uid", 0 )
		profile = self.get_profile ( uid = uid ) 
		return self.list_address ( id_profile = profile [ 'id_profile' ] )

	#}}}
	#{{{ KIND
	#{{{def set_kind ( self, id_kind, descr = '', owner = 0 ):
	def set_kind ( self, id_kind, descr = '', owner = 0 ):
		values = { 'descr' : descr,
			   'owner' : owner }

		if not owner : 
			values [ 'owner' ] = self.liwe.pyhp.session.data.get ( "uid", 0 )

		if not id_kind:
			#create
			values [ 'created' ] =  '*NOW()'
			self.dbm.insert  ( 'address_book_address_kind', values )
			values [ 'id' ] = self.dbm.insert_id()
			return values
		
		self.dbm.update ( 'address_book_address_kind', values, 'id = %s' % id_kind )
		values [ 'id' ] = id_kind
		return values
	#}}}			
	#{{{def get_kind ( self, id_kind ):
	def get_kind ( self, id_kind = 0 ):
		if not id_kind: return []
		
		conds = 'id = %s' % id_kind	
		resp =  self.dbm.single_row ( 'address_book_address_kind', "*", conds )
		return resp
	#}}}
	#{{{def del_kind ( self, ids ):
	def del_kind ( self, ids= "" ):
		if not ids: return
		ids = ids.split ( "|" )
		str_ids = " ,".join ( ids )
		
		self.dbm.delete ( "address_book_address_kind", "id IN ( %s )" % str_ids )
	#}}}	
	#{{{def list_kind ( self, descr = '', quant = 10 start_point = 0, do_count = 0 ):
	def list_kind ( self, descr = '', quant = 10, start_point = 0, do_count = 0 ):
		conds = []
		if descr: conds.append ( "descr like '%%%s%%'" % descr )

		#if  self.liwe.pyhp.session.data.get ( "uid", 0 ) != 1:
			#conds.append ( 'owner = %s' %  self.liwe.pyhp.session.data.get ( "uid", 0 ) )
	
		tot_rows = self.dbm.count ( 'address_book_address_kind', 'uid', ' AND '.join ( conds ) )
		extras = ''	
		if do_count:
			extras = " LIMIT %s,%s" % ( start_point, quant )
	
		resp = self.dbm.all_rows ( 'address_book_address_kind', '*', ' AND '.join ( conds ), extras = extras )
		if not resp:
			resp = [] 
		return { "rows" : resp, "tot_rows" : tot_rows }
	#}}}
	#}}}
	#{{{STATI PROVINCE REGIONI
	#{{{def list_regioni ( liwe ):
	def list_regioni ( self ):
		resp = self.dbm.all_rows ( 'address_book_province' , 'regione', extras = "group by regione" )
		if not resp :
			resp = []
		return resp
	#}}}
	#{{{def list_province ( liwe, regione ):
	def list_province ( self, regione ):
		conds = []
		if regione: conds.append ( "regione = '%s'" % regione )
		resp = self.dbm.all_rows ( 'address_book_province', [ 'sigla', 'provincia', 'regione' ], conds =  ' and '.join ( conds ) )
		if not resp:
			resp = []
		resp.append ( { "sigla" : "XX", "provincia" : "Estero", "regione" : "Estero" } );
		return resp
	#}}}
	#{{{def list_stati ( self ):
	def list_stati ( self ):
		resp = self.dbm.all_rows ( 'address_book_stati', [ 'id_stato', 'stato' ] )
		if not resp:
			resp = []
		return resp
	#}}}
		
	def comune_search ( self, prov ):
		return self.dbm.all_rows ( "address_book_cap", [ "comu_cap" ], "prov_cap = '%s'" % prov, extras = "ORDER BY comu_cap", distinct = 1 ) or []

	def cap_search ( self, prov = '', city = '' ):
		conds = []

		if prov:   
			prov = prov.replace ( "'", "''" )
			conds.append ( "prov_cap = '%s'" % prov )
		if city: 
			city = city.replace ( "'", "''" )
			conds.append ( "comu_cap = '%s'" % city )
		
		return self.dbm.all_rows ( "address_book_cap", [ "capi_cap", "fraz_cap" ], ' AND '.join ( conds ), extras = "ORDER BY capi_cap", distinct = 1 ) or []


	#}}}
	#{{{CATEGORIES
	#{{{def set_categ ( self, text, parent_id = 0, id_node = None ):
	def set_categ ( self, text, parent_id = 0, id_node = None ):
		uid = self.liwe.pyhp.session.data.get ( "uid", 0 )


		if id_node and int ( id_node ):
			dct = { "text" : text, "params" : "" }
			if parent_id: dct [ 'id_parent' ] = parent_id
			
			self.tree.change_attrs ( id_node, dct )
		else:
			id_node = self.tree.add_node ( uid, "address_book", text, "", id_parent = parent_id, params = '' )
			if parent_id:
				self.tree.change_attrs ( parent_id, { 'folder': 1 } )

		return id_node
	#}}}
	#{{{def list_am_categories ( self, start_point = 0, limit = 10 ):
	def list_am_categories ( self, start_point = 0, limit = 10 ):
                tot_rows = 0
                tot_rows = self.dbm.count ( 'liwe_tree_node', [ 'id' ] , "id_parent=0 and section='address_book'" )
                        
                extra = " LIMIT %s, %s" % ( start_point, limit )
                res = self.dbm.all_rows ( 'liwe_tree_node','*', "id_parent=0 and section ='address_book'", extras = extra )

                if not res:
                        res = []
                return { "rows" : res, "tot_rows" : tot_rows }
	#}}}
	#{{{def list_am_sub_categories ( self, id_parent, start_point = 0, limit = 10 ):
	def list_am_sub_categories ( self, id_parent, start_point = 0, limit = 10 ):
		if not id_parent :   return { "rows" : [], "tot_rows" : 0 }

                tot_rows = 0
                tot_rows = self.dbm.count ( 'liwe_tree_node', [ 'id' ] , "id_parent=%s and section='address_book'" % id_parent )
                        
                extra = " LIMIT %s, %s" % ( start_point, limit )
                res = self.dbm.all_rows ( 'liwe_tree_node','*', "id_parent=%s and section ='address_book'" % id_parent, extras = extra )

                if not res:
                        res = []
                return { "rows" : res, "tot_rows" : tot_rows }
	#}}}
	#{{{def list_categs ( self, id_node = 0 ):
	def list_categs ( self, id_node = 0 ):
		return self.tree.get_all_tree ( 'address_book', id_node )
	#}}}
	#{{{def get_categ ( self, id_categ ):
	def get_categ ( self, id_categ ):
		return self.tree.get_node ( 'address_book', id_categ )
	#}}}
	#{{{def del_category ( self, id_categ ):
	def del_category ( self, id_categ ):

		ids = id_categ.split ( '|' )
		id_to_check = ids
		for id in ids:
			lst_subcat = [ str ( x [ 'id' ] ) for x in self.list_categs ( id ) ] ;
			id_to_check += lst_subcat

		tot_ab = self.dbm.count ( 'address_book_profile', [ 'uid' ] , " id_categ in ( %s ) " % (',').join ( id_to_check  ) )
			
		if ( tot_ab ) : 
			self.liwe.set_error ( '1', 'Ci sono %s profili legati alla categoria o alle sottocategorie' % tot_ab )
			return []

		for id in ids:	
			res = self.tree.del_node ( 'address_book', id )

		return res
	#}}}
	#}}}
